package com.boot.util;

import com.boot.dao.JdbcTemplate;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;

/**
 * Created by xudi on 5/9/16.
 */
public class BatchInsertGisInfo extends JdbcTemplate {

    public static void main(String[] args) {
        new BatchInsertGisInfo().insert();
    }

    public void insert() {
        Connection conn = getConnection();
        String sql = "insert into building_gps_info_test(building_id,jwd,dt,building_name) " +
                "values(?,ST_Transform(ST_GeomFromText(?, 4326),2163),current_timestamp,?);";
        PreparedStatement ps = null;
        try {
            ps =conn.prepareStatement(sql);
            final int batchSize = 500;
            int count = 0;
            for (int i=1;i<=1000000;i++) {
                String jwd=randomLonLat(80,130,8,50);
                String point="POINT("+jwd+")";
                ps.setInt(1, i);
                ps.setString(2, point);
                ps.setString(3, point);
                ps.addBatch();
                if (++count % batchSize == 0) {
                    ps.executeBatch();
                    System.out.println("已提交"+count);
                }
            }
            ps.executeBatch();
            System.out.println("done!!!");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            free(null, ps, conn);
        }
    }

    public static String randomLonLat(double min1, double max1,double min2, double max2) {
        BigDecimal db = new BigDecimal(Math.random() * (max1 - min1) + min1);
        String lon = db.setScale(6, BigDecimal.ROUND_HALF_UP).toString();
        db = new BigDecimal(Math.random() * (max2 - min2) + min2);
        String lat = db.setScale(6, BigDecimal.ROUND_HALF_UP).toString();
        return lon+" "+lat;
    }
}
